import React, { Component } from 'react';
// 产品的主页面
import { Card, Select, Input, Button, Table, message, Tag } from 'antd';
import {
    PlusOutlined,
    SearchOutlined,
    CheckCircleOutlined,
    MinusCircleOutlined
} from '@ant-design/icons';
import { reqProduction, reqSearchProduction, reqUpDownProduction } from '../../api';
import { Link } from 'react-router-dom';
import store from '../../store';

const { Option } = Select;
class ProductHome extends Component {
    constructor(props) {
        super();
        this.state = {
            isLoading: store.getState().isLoading,
            searchTitle: 'id',
            searchInfo: '',
            // category: {},
            card: {
                title: (<>
                    <Select defaultValue="id" style={{ width: 150 }} onChange={this.handleChange}>
                        <Option value='id'>编号搜索</Option>
                        <Option value='name'>按关键字搜索</Option>
                    </Select>
                    <Input
                        style={{ width: '140px', margin: '0px 20px' }}
                        placeholder='关键字'
                        // value={this.state.searchInfo}
                        onChange={this.setSearchValue}
                    ></Input>
                    <Button
                        type="primary"
                        onClick={this.search}
                        icon={<SearchOutlined />
                        }>搜索</Button>
                </>),
                extra: (
                    <Link to='/product/addUpdate'>
                        <Button type="primary" shape="round" icon={<PlusOutlined />} style={{ padding: '3px 10px' }} onClick={this.addData}>
                            添加商品
                        </Button>
                    </Link>
                ),
            },
            tableData: [], // 表格数据
            columns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                },
                {
                    title: '编号',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '类别',
                    dataIndex: 'typeid',
                    key: 'typeid',
                    render: (text) => {
                        // try {
                        //     let reqRes = await reqGetCategory()
                        //     let arr = reqRes.data
                        //     // console.log(arr);
                        //     for (let i = 0; i < arr.length; i++) {
                        //         if (text == arr[i].id) {
                        //             return arr[i].typename.toString();
                        //         }
                        //     }
                        // } catch {
                        //     return '类别获取失败'
                        // }
                        // =============上方代码有错误(不能有异步？)==================
                        switch (text) {
                            case '001':
                                return '新能源'
                                break;
                            case '002':
                                return '轿车'
                                break;
                            case '003':
                                return 'SUV'
                                break;
                            case '004':
                                return 'MPV'
                                break;
                            case '005':
                                return '卡车'
                                break;
                            case '006':
                                return '皮卡'
                                break;
                            case '007':
                                return '微面'
                                break;
                            case '008':
                                return '微卡'
                                break;
                            case '009':
                                return '轻客'
                                break;
                            default:
                                return '未知分类编号:' + text;
                                break;
                        }
                    }
                },
                {
                    title: '名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '价格',
                    dataIndex: 'price',
                    key: 'price',
                    render: (text) => {
                        return text + '万起'
                    }
                },
                {
                    title: '状态',
                    dataIndex: 'state',
                    key: 'state',
                    render: (text, recoding, index) => {
                        if (text == '1') {
                            return (<>
                                <Tag color='green' icon={<CheckCircleOutlined />}>在售</Tag>
                                <Button
                                    size='small'
                                    onClick={() => { this.putDown(recoding, index) }}
                                >下架</Button>
                            </>)
                        } else if (text == '0') {
                            return (<>
                                <Tag color='red' icon={<MinusCircleOutlined />}>已下架</Tag>
                                <Button
                                    size='small'
                                    onClick={() => { this.putOn(recoding, index) }}
                                >发售</Button>
                            </>)
                        }
                    }
                },
                {
                    title: '操作',
                    dataIndex: '',
                    key: 'name',
                    render: (text) => {
                        return (
                            <>
                                <Link to={{
                                    pathname: '/product/detail',
                                    state: text
                                }} > [查看详情] </Link><br />
                                <Link to={{
                                    pathname: '/product/update',
                                    state: text
                                }}> [修改此项] </Link>
                            </>
                        )
                    }
                },
            ],
        }
    };
    //  constructor=======================================
    // 上架下架
    putOn = (recoding, index) => {
        recoding.state = 1
        // 后端更改
        reqUpDownProduction(recoding.id, recoding).then(res => {
            if (res.data.length != 0) {
                //前端更改
                let cover = this.state.tableData;
                cover[index].state = 1;
                this.setState({
                    tableData: cover
                })
                message.success('更改成功')
            } else {
                message.success('更改失败')
            }
        })
    }
    putDown = (recoding, index) => {
        recoding.state = 0
        // 后端更改
        reqUpDownProduction(recoding.id, recoding).then(res => {
            if (res.data.length != 0) {
                //前端更改
                let cover = this.state.tableData;
                cover[index].state = 0;
                this.setState({
                    tableData: cover
                })
                message.success('更改成功')
            } else {
                message.success('更改失败')
            }
        })
    }
    // 搜索产品
    setSearchValue = (ev) => {
        this.setState({
            searchInfo: ev.target.value
        })
    }
    search = () => {
        if (this.state.searchInfo != '') {
            if (this.state.searchTitle == 'name') {
                reqSearchProduction(this.state.searchInfo).then(res => {
                    if (res.data) {
                        res.data.forEach((item, index) => {
                            item.index = index + 1
                        })
                        this.setState({
                            tableData: res.data
                        })
                    } else {
                        message.error('查找出错')
                    }
                })
            } else {
                reqProduction(this.state.searchInfo).then(res => {
                    if (res.data.length >= 0) {
                        res.data.forEach((item, index) => {
                            item.index = index + 1
                        })
                        this.setState({
                            tableData: res.data
                        })
                    } else {
                        message.error('查找出错')
                    }
                })
            }
        }else{
            message.error('查找出错');
        }
    }
    // 按什么搜索
    handleChange = (value) => {
        this.setState({
            searchTitle: value
        })
    }

    // static getDerivedStateFromProps(){
    //     let isLoading = store.getState().isLoading;
    //     return {isLoading:isLoading}
    // }
    async componentDidMount() {
        store.subscribe(() => {
            this.setState({
                isLoading: store.getState().isLoading
            })
        });
        // 获取产品信息
        store.dispatch({ type: 'toTrue' });
        reqProduction().then(res => {
            if (res.data) {
                res.data.forEach((item, index) => {
                    item.index = index + 1
                });
                this.setState({
                    tableData: res.data
                },
                    () => {
                        store.dispatch({ type: 'toFalse' })
                    }
                )
            } else {
                message.error('数据出错了...')
            }
        })
    }

    render() {
        return (
            < >
                {/* <p>{store.getState().count}</p> */}
                <Card title={this.state.card.title} extra={this.state.card.extra} style={{ width: '100%', height: '100%' }}>
                    <Table
                        loading={this.state.isLoading}
                        pageSize='10'
                        rowKey='id'
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                    ></Table>
                </Card>
            </>
        );
    }
}

export default ProductHome;